package com.jdl.iscm.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Ran
 * @Date: 2021/8/18
 **/
@Configuration
public class RedisCacheClient implements CacheClient {


    /**
     * stringRedisTemplate
     */
    private final StringRedisTemplate stringRedisTemplate;

    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 构造函数
     *
     * @param stringRedisTemplate
     */
    public RedisCacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public List<String> mGet(String... keys) {
        return stringRedisTemplate.opsForValue().multiGet(Arrays.asList(keys));
    }

    @Override
    public void del(String... keys) {
        stringRedisTemplate.delete(Arrays.asList(keys));
    }

    @Override
    public void mSetString(Map<String, String> tuples) {
        stringRedisTemplate.opsForValue().multiSet(tuples);
    }

    @Override
    public void del(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public long incr(String key) {
        return stringRedisTemplate.opsForValue().increment(key);
    }

    @Override
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    @Override
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    @Override
    public boolean setNx(String key, String value) {
        return stringRedisTemplate.opsForValue().setIfAbsent(key, value);
    }

    @Override
    public String lPop(String key) {
        return stringRedisTemplate.opsForSet().pop(key);
    }

    @Override
    public String sPop(String key) {
        return stringRedisTemplate.opsForSet().pop(key);
    }

    @Override
    public void sAdd(String key, String... values) {
        stringRedisTemplate.opsForSet().add(key, values);
    }

    @Override
    public String hGet(String key, String field) {
        Object obj = stringRedisTemplate.opsForHash().get(key, field);
        if (obj == null) {
            return null;
        }
        return obj.toString();
    }

    @Override
    public boolean expire(String key, long timeout, TimeUnit unit) {
        return stringRedisTemplate.expire(key, timeout, unit);
    }

    @Override
    public boolean exists(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    @Override
    public Object getObject(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public void setObject(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);

    }
}
